package com.visitorspecials.tankbattle;

import java.io.IOException;
import java.io.InputStream;
import java.io.PrintStream;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;

import com.visitorspecials.tankbattle.server.HelperFuncs;
import com.visitorspecials.tankbattle.server.TankBattleServer;

import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.opengl.GLSurfaceView;
import android.view.MotionEvent;

public class TankBattleGlSurfaceView extends GLSurfaceView implements
		SensorEventListener
{
	private SensorManager sensorManager;
	private Sensor accelerometer;
	private Socket s;
	private PrintStream ps;
	/** Called when the activity is first created. */

	private OpenGLRenderer renderer;

	private Sprite background;

	private float[] accXRunningAverage = new float[5];
	private float[] accYRunningAverage = new float[5];
	private int accIdx = 0;

	public TankBattleGlSurfaceView(Context context)
	{
		super(context);
		
		

		renderer = new OpenGLRenderer();
		this.setRenderer(renderer);

		this.setRenderMode(RENDERMODE_WHEN_DIRTY);

		this.background = new Sprite("back", 0, 0, 0, 2, 0, 1, 0, 1);

		sensorManager = (SensorManager) context
				.getSystemService(Context.SENSOR_SERVICE);
		accelerometer = sensorManager
				.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
		sensorManager.registerListener(this, accelerometer,
				SensorManager.SENSOR_DELAY_NORMAL);

		testSpriteParsing();

		try
		{
			TankBattleServer server = new TankBattleServer();
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}

		try
		{
			s = new Socket("localhost", 12345);
			ps = new PrintStream(s.getOutputStream());
			this.networkListenLoop(s);
		}
		catch (UnknownHostException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		catch (IOException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	private void testSpriteParsing()
	{
		renderer.drawObjectsLock = true;

		Sprite s = HelperFuncs
				.parseStringToSprite("test:0.000000:0.000000:0.000000:0.100000");
		s.toString();

		/*
		 * The format for these strings is as follows:
		 * ::textureName:x:y:rotation:width Lather, rinse, and repeat.
		 */

		// t = HelperFuncs.parseStringToSprite("test:0:0:0:1.3");
		// this.renderer.drawObjects.add(t);
		renderer.drawObjectsLock = false;
	}

	@Override
	public boolean onTouchEvent(MotionEvent e)
	{
		float x = e.getRawX();
		float y = e.getRawY();
		
		x = (renderer.width - x) / renderer.width;
		y = (renderer.height - y) / renderer.height;

		y = y * 2 - 1;
		x = x * 2 - 1;
		
		ps.println(String.format("T:%f:%f", y, -x));
		
		return true;
	}

	@Override
	public void onAccuracyChanged(Sensor arg0, int arg1)
	{
		// TODO Auto-generated method stub

	}

	@Override
	public void onSensorChanged(SensorEvent arg0)
	{
		if (accIdx == accXRunningAverage.length)
			accIdx = 0;

		accXRunningAverage[accIdx] = arg0.values[0];
		accYRunningAverage[accIdx++] = arg0.values[1];

		float x = HelperFuncs.averageArray(accXRunningAverage) / 15;
		float y = HelperFuncs.averageArray(accYRunningAverage) / 15;

		if (ps != null)
			ps.println(String.format("A:%f:%f", -x, -y));
	}

	private boolean isRunning = false;

	private void networkListenLoop(final Socket serverSocket)
	{
		this.isRunning = true;

		new Thread(new Runnable() {
			@Override
			public void run()
			{
				try
				{
					InputStream is = serverSocket.getInputStream();
					Scanner s = new Scanner(is);

					while (isRunning)
					{
						// try
						// {
						String line = s.nextLine();

						if(line.length() < 5)
							continue;
						
						while (renderer.drawObjectsLock)
							;

						renderer.drawObjectsLock = true;
						renderer.drawObjects.clear();

						renderer.drawObjects.add(background);

						for (Sprite sprt : HelperFuncs
								.parseStringToSprites(line))
						{
							renderer.drawObjects.add(sprt);
						}

						renderer.drawObjectsLock = false;

						requestRender();
						// }
						// catch (Exception exc)
						// {
						// int i = 0;
						// }
					}
				}
				catch (Exception exc)
				{

				}
			}
		}).start();
	}

}

